import React, { useEffect, useState, useRef } from 'react';
import { Button, Form, Input, Spin, Modal, Tooltip, Space, Typography, message, Divider } from 'antd';
import { 
  UserOutlined, 
  LockOutlined, 
  SafetyOutlined, 
  GlobalOutlined, 
  InfoCircleOutlined, 
  EyeTwoTone,
  EyeInvisibleOutlined,
  ArrowRightOutlined
} from '@ant-design/icons';
import { useAuth } from '../../hooks/authHooks';
import { useNavigate, useLocation } from 'react-router-dom';
import './Login.scss';
import auth from '../../utils/auth';
import logo from '../../assets/images/logo.jpg';

const { Text } = Typography;

// 添加调试信息
console.log('Login组件已加载');

interface LoginForm {
  username: string;
  password: string;
  captcha: string;
}

// 定义验证码响应类型
type CaptchaResponse = {
  type: 'svg' | 'blob';
  data: string | Blob;
};

// 简化版通知工具
const Notify = {
  success: (msg: string) => message.success(msg),
  error: (msg: string) => message.error(msg),
  warning: (msg: string) => message.warning(msg),
  info: (msg: string) => message.info(msg)
};

const Login: React.FC = () => {
  const { login, loading: isLoading, error } = useAuth();
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const location = useLocation();
  const [forgotModalVisible, setForgotModalVisible] = useState(false);
  const [captchaUrl, setCaptchaUrl] = useState('');
  const [captchaLoading, setCaptchaLoading] = useState(true);
  const errorProcessedRef = useRef(false);
  
  // 记录登录页面加载，辅助调试
  console.log('登录页面路由状态:', { 
    pathname: location.pathname, 
    state: location.state, 
    search: location.search 
  });
  
  useEffect(() => {
    // 加载验证码
    refreshCaptcha();
    
    // 添加动画类
    document.body.classList.add('dark-theme');
    
    return () => {
      document.body.classList.remove('dark-theme');
    };
  }, []);
  
  // 刷新验证码
  const refreshCaptcha = () => {
    // 设置加载状态
    setCaptchaLoading(true);
    
    // 添加时间戳防止缓存
    const timestamp = new Date().getTime();
    // 验证码API路径
    const captchaApiUrl = `/adminapi/captcha?t=${timestamp}`;
    
    // 使用Fetch API获取验证码图片
    fetch(captchaApiUrl)
      .then(async (response) => {
        if (!response.ok) {
          throw new Error('验证码获取失败');
        }
        // 检查返回类型
        const contentType = response.headers.get('Content-Type');
        
        // 根据返回类型处理数据
        if (contentType && contentType.includes('image/svg+xml')) {
          const svgText = await response.text();
          return { type: 'svg', data: svgText } as CaptchaResponse;
        } else {
          const blobData = await response.blob();
          return { type: 'blob', data: blobData } as CaptchaResponse;
        }
      })
      .then((result: CaptchaResponse) => {
        if (result.type === 'svg') {
          // 创建SVG的数据URL
          const imageUrl = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(result.data as string)}`;
          setCaptchaUrl(imageUrl);
        } else {
          // 如果是blob，创建blob URL
          const imageUrl = URL.createObjectURL(result.data as Blob);
          setCaptchaUrl(imageUrl);
        }
        setCaptchaLoading(false);
      })
      .catch(error => {
        console.error('验证码加载失败:', error);
        setCaptchaLoading(false);
        Notify.error('验证码加载失败，请点击刷新');
      });
  };
  
  // 检查是否已经登录
  useEffect(() => {
    const token = auth.getToken();
    const userInfo = auth.getUserInfo();
    
    // 检查URL参数，判断是否是因为登录过期被重定向
    const urlParams = new URLSearchParams(window.location.search);
    const expired = urlParams.get('expired');
    
    if (expired === 'true') {
      // 清理残留的token和用户信息
      auth.clearUserInfo();
      
      // 提示用户
      Notify.warning('您的登录已过期，请重新登录');
      
      // 清除URL参数
      window.history.replaceState({}, document.title, '/login');
      return;
    }
    
    if (token && userInfo) {
      // 如果已经登录，直接跳转到首页
      Notify.info('您已经登录，正在跳转到首页');
      navigate('/home');
    }
  }, [navigate]);
  
  // 监听错误，如果是验证码错误，自动刷新验证码
  useEffect(() => {
    if (error && (error.includes('验证码') || error.includes('captcha'))) {
      refreshCaptcha();
      // 清空验证码输入框
      form.setFieldsValue({
        captcha: ''
      });
    }
  }, [error, form]);
  
  // 处理登录
  const onFinish = async (values: LoginForm) => {
    // 重置错误处理标记
    errorProcessedRef.current = false;
    
    // 基本验证
    if (!values.username.trim()) {
      Notify.error('用户名不能为空！');
      return;
    }
    
    if (!values.password.trim()) {
      Notify.error('密码不能为空！');
      return;
    }
    
    if (!values.captcha?.trim()) {
      Notify.error('验证码不能为空！');
      return;
    }
    
    try {
      // 使用登录钩子
      const result = await login({
        username: values.username,
        password: values.password,
        captcha: values.captcha,
      });
      
      // 检查登录是否成功
      if (result.success) {
        Notify.success('登录成功，正在跳转...');
        
        // 检查是否有重定向地址
        const redirectPath = location.state?.from?.pathname || '/home';
        
        // 立即导航到主页，避免使用setTimeout导致的循环问题
        navigate(redirectPath, { replace: true });
      }
    } catch {
      // 登录失败，刷新验证码
      if (!errorProcessedRef.current) {
        errorProcessedRef.current = true;
        refreshCaptcha();
        form.setFieldsValue({ captcha: '' });
      }
    }
  };
  
  // 处理忘记密码
  const handleForgotPassword = () => {
    setForgotModalVisible(true);
  };
  
  // 关闭忘记密码弹窗
  const handleForgotModalCancel = () => {
    setForgotModalVisible(false);
  };
  
  // 渲染登录表单
  return (
    <div className="login-container">
      {/* 背景元素 */}
      <div className="login-background">
        <div className="background-overlay"></div>
        <div className="light-effect light-effect-1"></div>
        <div className="light-effect light-effect-2"></div>
      </div>
      
      <div className="login-content">
        {/* 左侧品牌区域 */}
        <div className="login-brand">
          <div className="brand-content">
            <div className="brand-logo">
              <img src={logo} alt="Logo" onError={(e) => {
                e.currentTarget.src = 'https://via.placeholder.com/120x120?text=NEWS';
                e.currentTarget.onerror = null;
              }} />
            </div>
            <h1 className="brand-title">新闻发布管理系统</h1>
            <p className="brand-description">专业的企业级新闻内容管理平台</p>
            <div className="brand-features">
              <div className="feature-item">
                <div className="feature-icon">
                  <svg viewBox="0 0 24 24" width="24" height="24" stroke="currentColor" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline><line x1="16" y1="13" x2="8" y2="13"></line><line x1="16" y1="17" x2="8" y2="17"></line><polyline points="10 9 9 9 8 9"></polyline></svg>
                </div>
                <div className="feature-text">高效新闻管理</div>
              </div>
              <div className="feature-item">
                <div className="feature-icon">
                  <svg viewBox="0 0 24 24" width="24" height="24" stroke="currentColor" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path><circle cx="9" cy="7" r="4"></circle><path d="M23 21v-2a4 4 0 0 0-3-3.87"></path><path d="M16 3.13a4 4 0 0 1 0 7.75"></path></svg>
                </div>
                <div className="feature-text">多角色权限控制</div>
              </div>
              <div className="feature-item">
                <div className="feature-icon">
                  <svg viewBox="0 0 24 24" width="24" height="24" stroke="currentColor" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect><circle cx="8.5" cy="8.5" r="1.5"></circle><polyline points="21 15 16 10 5 21"></polyline></svg>
                </div>
                <div className="feature-text">数据可视化分析</div>
              </div>
            </div>
          </div>
        </div>
        
        {/* 右侧登录表单区域 */}
        <div className="login-form-wrapper">
          <div className="login-form-container">
            <div className="login-header">
              <h2>欢迎登录</h2>
              <p>请使用您的账号密码登录系统</p>
            </div>
            
            <Form
              name="login"
              form={form}
              initialValues={{ remember: false }}
              onFinish={onFinish}
              size="large"
              className="login-form"
            >
              <Form.Item
                name="username"
                rules={[{ required: true, message: '请输入用户名!' }]}
              >
                <Input 
                  prefix={<UserOutlined className="form-icon" />} 
                  placeholder="用户名" 
                  autoComplete="username"
                  className="login-input"
                />
              </Form.Item>
              
              <Form.Item
                name="password"
                rules={[{ required: true, message: '请输入密码!' }]}
              >
                <Input.Password
                  prefix={<LockOutlined className="form-icon" />}
                  placeholder="密码"
                  autoComplete="current-password"
                  className="login-input"
                  iconRender={visible => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
                />
              </Form.Item>
              
              <Form.Item
                name="captcha"
                rules={[{ required: true, message: '请输入验证码!' }]}
              >
                <div className="captcha-container">
                  <Input 
                    prefix={<SafetyOutlined className="form-icon" />}
                    placeholder="验证码"
                    className="login-input captcha-input"
                  />
                  <div className="captcha-image-wrapper" onClick={refreshCaptcha}>
                    {captchaLoading ? (
                      <div className="captcha-loading">
                        <Spin size="small" />
                      </div>
                    ) : (
                      <img 
                        src={captchaUrl} 
                        alt="验证码" 
                        className="captcha-image"
                        title="点击刷新验证码"
                      />
                    )}
                  </div>
                </div>
              </Form.Item>
              
              <Form.Item className="form-actions">
                <Button type="link" onClick={handleForgotPassword} className="forgot-btn">
                  忘记密码?
                </Button>
              </Form.Item>
              
              <Form.Item className="login-submit-container">
                <Button 
                  type="primary" 
                  htmlType="submit" 
                  className="login-btn"
                  loading={isLoading}
                  block
                >
                  <span>登录系统</span>
                  <ArrowRightOutlined className="btn-icon" />
                </Button>
              </Form.Item>
            </Form>
            
            <div className="login-footer">
              <Divider className="footer-divider">安全说明</Divider>
              <p className="security-tips">登录即代表您已同意<a href="#">《用户协议》</a>和<a href="#">《隐私条款》</a></p>
            </div>
          </div>
        </div>
      </div>
      
      <div className="system-info">
        <Space>
          <Text>新闻发布管理系统 &copy; {new Date().getFullYear()}</Text>
          <Tooltip title="系统信息">
            <InfoCircleOutlined />
          </Tooltip>
          <Tooltip title="切换语言">
            <GlobalOutlined />
          </Tooltip>
        </Space>
      </div>
      
      {/* 忘记密码模态框 */}
      <Modal
        title="找回密码"
        open={forgotModalVisible}
        onCancel={handleForgotModalCancel}
        footer={[
          <Button key="cancel" onClick={handleForgotModalCancel}>
            取消
          </Button>,
          <Button key="submit" type="primary" onClick={handleForgotModalCancel}>
            提交
          </Button>,
        ]}
        className="forgot-modal"
      >
        <p>请联系系统管理员重置密码</p>
      </Modal>
    </div>
  );
};

export default Login;


// 深色主题专业风格
// 深色背景配合高对比度元素
// 大型企业LOGO展示区
// 精致阴影与微动效
// 登录区域高亮处理
// 更加突出的按钮设计
// 动态光效设计（如按钮悬停效果）